import os
import json
from src.common import MessageQueue
from src.common.logger import getLogger
from src.modules.common.service import common_service
from flask import Blueprint, Response, request, stream_with_context

logger = getLogger()
api = Blueprint('common', __name__)

@api.route('/info')
def info():
    return 'Hello. TaiXu-人工智能系统!'

@api.route('/common/code')
def generate_captcha():
    image_base64, image_text = common_service.generate_captcha_image(length = 4)
    data = { "code": 200, "data": { "image_base64": image_base64, "image_text": image_text } }
    return Response(json.dumps(data), status = 200, mimetype = 'image/json')

@api.route('/common/download_image')
def download_image():
    image_path = request.args.get("image_path")
    if not os.path.exists(image_path):
        return Response("没有找到对应的文件", status = 200, mimetype = 'application/json')

    image_data = open(image_path, 'rb').read()
    return Response(image_data, status = 200, mimetype = 'image/png')

@api.route('/common/message')
def message_stream():
    stream_context = stream_with_context(MessageQueue.extract_event_message())
    return Response(stream_context, mimetype = "text/event-stream", headers = { 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' })
